<!--------------- CS143: Project 1A ----------------------------
--- Author: Chelsea Ju -----------------------------------------
--- Date: 2012/04/12 ------------------------------------------->

<HTML>
<H1> CS143: Project 1A - Calculator </H1>

<BODY>
<FORM action="calculator.php" method = "get">
   <h3>Please give an arithmetic expression (ex: 2+3*2.6 = 9.8): </b></h3>
   <INPUT type = "text" name = "arithmetic"/>
   <INPUT type = "submit" value="Calculate"/>
   </FORM>
   
   <ul>
   <li>Only numbers (integers or real numbers) and arithmetic operators (+ - * /) are allowed</li>
   <li>This calculator does not support parentheses.</li>
   </ul>

   <br/>
		
   <!------- display result here ------>

   <?php
   ini_set( "display_errors", 0);  // hide the error message from webpage
if(count($_GET)>0 && $_GET["arithmetic"] != ""){
  echo "<h2>Result</h2>\n";
  $raw_input = $_GET["arithmetic"];
  $input = preg_replace("#\s+#","",$raw_input);	 // remove space			
  $expression = "#^\-?\d+(\.\d+)?([\+\*/]?\-?\d+(\.\d+)?)*$#";

  // attempt to handle divided by zero case
//  $divided_by_zero = "#/0(.0+)?[1-9]{0}([\+\*/]?\-?\d(\.\d+)?)*$#"; 
//  preg_match($divided_by_zero, $input, $zero_match);
//  echo count($zero_match)."<br/>";
 
  preg_match($expression, $input, $match);

  if(count($match) > 0){
    eval("\$output = $input;");
    echo $raw_input." = ".$output;					
  }
  else{
    echo "Invalid input expression: ".$input;
  }
  
}
?>

</BODY>
</HTML>